package com.luoqiz.file.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/doc")
public class DocFileController {

	// 在线预览
	@RequestMapping("/onlinePreview")
	public void onlinePreview(String filePath, HttpServletResponse response) {
		BufferedInputStream br;
		OutputStream out;
		filePath = "D:/watermark.pdf";
		try {
			File file = null;
			String[] split = filePath.split("\\.");
			if (!"pdf".equals(split[split.length - 1])) {
				if (!new File(filePath.substring(0, filePath.lastIndexOf(".")) + ".pdf").exists()) {
//					file = Office2PDF.openOfficeToPDF(filePath);
				} else {
					file = new File(filePath.substring(0, filePath.lastIndexOf(".")) + ".pdf");
				}
			} else {
				file = new File(filePath);
			}
			br = new BufferedInputStream(new FileInputStream(file));
			byte[] buf = new byte[1024];
			int len = 0;
			response.reset(); // 非常重要
			response.setContentType("application/pdf");
			response.setHeader("Content-Disposition",
					"inline; filename=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
			out = response.getOutputStream();
			while ((len = br.read(buf)) != -1)
				out.write(buf, 0, len);
			br.close();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
